package com.example.clientmanage

import android.content.Intent
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.widget.Toast
import androidx.annotation.RequiresApi
import com.example.clientmanage.databinding.ActivityRegisterBinding

class RegisterActivity : AppCompatActivity() {
    lateinit var binding: ActivityRegisterBinding
    lateinit var handler: Handler
    @RequiresApi(Build.VERSION_CODES.S)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding= ActivityRegisterBinding.inflate(layoutInflater)
        setContentView(binding.root)
        handler = object : Handler(){
            override fun handleMessage(msg: Message) {
                if (msg.what==1){
                    if(msg.obj.toString()=="T"){
                        Toast.makeText(this@RegisterActivity,"注册成功！",Toast.LENGTH_SHORT).show()
                        val intent= Intent(this@RegisterActivity, LoginActivity::class.java)
                        startActivity(intent)
                        finish() // 关闭当前注册活动，防止用户返回到注册界面
                    }else{
                        Toast.makeText(this@RegisterActivity,"注册失败！",Toast.LENGTH_SHORT).show()
                    }
                }
            }
        }
        binding.btnRegister.setOnClickListener {
            val name=binding.etName.text.toString()
            val pwd1=binding.etPwd.text.toString()
            val pwd2=binding.etPwd2.text.toString()
            //lvv 先验证输入是否为空
            if (name.isEmpty() || pwd1.isEmpty() || pwd2.isEmpty()) {
                Toast.makeText(this,"用户名和密码不能为空！",Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            
            // 先验证密码一致性
            if(pwd1.equals(pwd2)) {
                // 密码一致，发送网络请求
                var url = "http://192.168.229.24:8080/clientManage/servlet/RegisterServlet"
                url = url+"?name=$name&pwd=$pwd1"
                val conByGetHttp = ConByGetHttp(url, handler)
                conByGetHttp.start()
            } else {
                Toast.makeText(this,"两次密码不一致！",Toast.LENGTH_LONG).show()
            }
        }
    }
}